from fastapi import APIRouter, Request, Depends
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from jose import jwt, JWTError
from auth.db import SessionLocal
from auth.utils import SECRET_KEY, ALGORITHM
from devices.models import Device
from ecg.models import ECGRecord

router = APIRouter()
templates = Jinja2Templates(directory="templates")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_current_user(request: Request):
    token_cookie = request.cookies.get("access_token")
    if not token_cookie:
        return None
    try:
        token = token_cookie.split(" ")[1]
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload.get("sub")
    except JWTError:
        return None

# ECG 首页 → 显示设备列表
@router.get("/ecg", response_class=HTMLResponse)
def ecg_home(request: Request, db: Session = Depends(get_db)):
    username = get_current_user(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)
    devices = db.query(Device).filter(Device.owner == username).all()
    return templates.TemplateResponse("ecg_list.html", {
        "request": request,
        "username": username,
        "devices": devices,
        "records": None
    })

# 查看设备的数据记录列表
@router.get("/ecg/{device_id}", response_class=HTMLResponse)
def ecg_records(device_id: str, request: Request, db: Session = Depends(get_db)):
    username = get_current_user(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)
    records = db.query(ECGRecord).filter(
        ECGRecord.owner == username,
        ECGRecord.device_id == device_id
    ).order_by(ECGRecord.start_time.desc()).all()
    return templates.TemplateResponse("ecg_list.html", {
        "request": request,
        "username": username,
        "device_id": device_id,
        "records": records
    })

# 查看具体数据波形
@router.get("/ecg/view/{record_id}", response_class=HTMLResponse)
def ecg_view(record_id: int, request: Request, db: Session = Depends(get_db)):
    username = get_current_user(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)
    record = db.query(ECGRecord).filter(ECGRecord.id == record_id, ECGRecord.owner == username).first()
    if not record:
        return RedirectResponse(url="/ecg", status_code=303)

    # 将字符串 ECG 数据转成 float 列表
    samples = [float(x) for x in record.data.split(",")[:1000]]  # 限制最多1000点演示
    return templates.TemplateResponse("ecg_detail.html", {
        "request": request,
        "username": username,
        "record": record,
        "samples": samples
    })
